package yourapp.expense.service;

import yourapp.expense.dto.StatisticsDTO;
import yourapp.expense.entity.Expense;
import java.math.BigDecimal;
import java.util.List;

public class StatisticsService {
  public StatisticsDTO calculateStats(List<Expense> expenses) {
    StatisticsDTO stats = new StatisticsDTO();
    if (expenses == null || expenses.isEmpty()) {
      return stats;
    }

    BigDecimal max = expenses.get(0).getAmount();
    BigDecimal min = expenses.get(0).getAmount();
    BigDecimal sum = BigDecimal.ZERO;
    Expense maxExpense = expenses.get(0);
    Expense minExpense = expenses.get(0);

    for (Expense e : expenses) {
      BigDecimal amount = e.getAmount();
      sum = sum.add(amount);
      if (amount.compareTo(max) > 0) {
        max = amount;
        maxExpense = e;
      }
      if (amount.compareTo(min) < 0) {
        min = amount;
        minExpense = e;
      }
    }

    BigDecimal avg = sum.divide(new BigDecimal(expenses.size()), 2, BigDecimal.ROUND_HALF_UP);

    stats.setMaxAmount(max);
    stats.setMaxExpense(maxExpense);
    stats.setMinAmount(min);
    stats.setMinExpense(minExpense);
    stats.setAvgAmount(avg);

    return stats;
  }
}